﻿using Abp.Authorization;
using Abp.Specifications;
using Paas.App.Interface.Common;
using Paas.App.Interface.Common.Dtos;
using Paas.App.Interface.Common.Messages;
using Paas.Core;
using Paas.Core.Sys.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Basefr.App;
using Basefr.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Paas.App.Common
{
    [Route("SelectSearch")]
    [AbpAuthorize()]
    public class SelectSearchAppService : AppService, ISelectSearchAppService
    {
        private readonly IMainRepository<User, long> _userRepo;

        public SelectSearchAppService(IMainRepository<User, long> userRepo)
        {
            _userRepo = userRepo;
        }

        [HttpPost(nameof(SelectSearchUser))]
        public virtual SelectSearchUserOutput SelectSearchUser(SelectSearchUserInput input)
        {
            Expression<Func<User, bool>> predicate = p => p.IsActive;

            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                var name = input.Name.Trim();
                predicate = predicate.And(p => p.Name.Contains(name) || p.UserName.Contains(name));
            }

            var result = _userRepo.GetAll()
                .Include(p => p.Organization.Parent.Parent.Parent.Parent.Parent)
                .Where(predicate)
                .OrderByDescending(p => p.Id)
                .GetPage(input.SkipCount, input.MaxResultCount, out var total, out var isOverPaged)
                .ToList();

            return new SelectSearchUserOutput { Items = ObjectMapper.Map<List<UserSelectDto>>(result), TotalCount = total, IsOverPaged = isOverPaged };
        }
    }
}

